package Rangel.common.world.entity;

import Rangel.common.world.sorter.IntersectionSorter;
import rescuecore2.misc.Pair;
import rescuecore2.misc.geometry.Line2D;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import Rangel.common.world.info.LineInfo;

public class Ray implements Serializable {
    private static final long serialVersionUID = 2171584567647208229L;
    private Line2D ray;
    private List<LineInfo> hit;


    public Ray(Line2D ray, Collection<LineInfo> otherLines) {
        this.ray = ray;
        List<Pair<LineInfo, Double>> intersections = new ArrayList<>();
        for (LineInfo other : otherLines) {
            double d1 = ray.getIntersection(other.getLine());
            double d2 = other.getLine().getIntersection(ray);
            if (d2 >= 0 && d2 <= 1 && d1 > 0 && d1 <= 1) {
                intersections.add(new Pair<>(other, d1));
            }
        }
        IntersectionSorter intersectionSorter = new IntersectionSorter();

        intersections.sort(intersectionSorter);
        hit = new ArrayList<>();
        for (Pair<LineInfo, Double> next : intersections) {
            LineInfo l = next.first();
            hit.add(l);
            if (l.isBlocking()) {
                break;
            }
        }
    }

    public Line2D getRay() {
        return ray;
    }

    public List<LineInfo> getLinesHit() {
        return Collections.unmodifiableList(hit);
    }

}
